﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Juntas;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.PermisosModule.Resources;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Areas
{
	public partial class AreasViewModel
	{
		#region Private properties

		private List<Junta> _juntas;

		private Junta _junta;

		#endregion

		public List<Junta> Juntas
		{
			get
			{
				return _juntas;
			}
			private set
			{
				_juntas = value;
				if (value != null)
				{
					RaisePropertyChanged("Juntas");
				}
			}
		}

		public Junta Junta
		{
			get
			{
				return _junta;
			}
			private set
			{
				_junta = value;
				if (_junta != null)
					RaisePropertyChanged("Junta");
			}
		}

		private void LoadJuntas()
		{
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IJuntaService juntaService = IoCFactory.Resolve<IJuntaService>();
					e.Result = juntaService.FindJuntasByEstado(new Guid("B13F5C3F-AA42-4943-A8E9-49BA546EE5D1"));
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					if (!e.Cancelled && e.Error == null)
						Juntas = e.Result as List<Junta>;
					else if (e.Error != null)
						MessageBox.Show(_areasView, e.Error.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		private void OnJuntasPropertyChanged()
		{
			_areasView.juntaBindingSource.DataSource = Juntas;
			_areasView.juntaBindingSource.CurrentChanged += SetCurrentJunta;
			SetCurrentJunta(_areasView.juntaBindingSource, new EventArgs());
		}

		private void OnJuntaPropertyChanged()
		{
			LoadAreas();
		}

		private void SetCurrentJunta(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null)
				if (bindingSource.Current != null)
					Junta = bindingSource.Current as Junta;
		}
	}
}
